package signal

import (
	"context"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/openeuler/uos-libvirtd-exporter/collector"
	"gitee.com/openeuler/uos-libvirtd-exporter/slogx"
)

// Handler handles OS signals for graceful shutdown
type Handler struct {
	collector *collector.LibvirtCollector
	sigChan   chan os.Signal
}

// NewHandler creates a new signal handler
func NewHandler(collector *collector.LibvirtCollector) *Handler {
	return &Handler{
		collector: collector,
		sigChan:   make(chan os.Signal, 1),
	}
}

// Start starts listening for signals and returns a context that will be cancelled on signal
func (s *Handler) Start() context.Context {
	ctx, cancel := context.WithCancel(context.Background())

	signal.Notify(s.sigChan, os.Interrupt, syscall.SIGTERM)

	go func() {
		sig := <-s.sigChan
		slogx.Info("Received shutdown signal", "signal", sig.String())
		cancel()
		s.shutdown()
	}()

	return ctx
}

// shutdown performs cleanup operations
func (s *Handler) shutdown() {
	slogx.Info("Starting graceful shutdown")
	if s.collector != nil {
		s.collector.Close()
	}
	slogx.Info("Shutdown complete")
}
